package com.roncoo.education.api;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/admin")
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class ImageUploadController {

    @Value("${file.upload-dir}")
    private String uploadDir;

    @PostMapping("/upload")
    public String uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            Map<String,String> ret = new HashMap<>();
            ret.put("code","fail");
            ret.put("msg","上传文件为空");
            return JSONUtil.toJsonStr(ret);
        }

        try {
            // Compress and convert image to Base64
            byte[] compressedImageBytes = compressImage(file, 1024);
            String base64Image = getBase64Image(compressedImageBytes);

            // Save the compressed image to the server
            String nowDate = DateUtil.today();
            Path uploadPath = Paths.get(uploadDir+nowDate+"/");
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            String extension = getFileExtension(file.getOriginalFilename());
            String fileName = "show"+DateUtil.format(new Date(),"yyyyMMddHHmmss")+"."+extension;
            Path filePath = uploadPath.resolve(fileName);
            Files.write(filePath, compressedImageBytes);

            // Return the Base64 image for preview
            Map<String,String> ret = new HashMap<>();
            ret.put("url","/"+nowDate+"/"+fileName);
//            ret.put("imageBase64",base64Image);
            ret.put("code","success");
            return JSONUtil.toJsonStr(ret);
        } catch (IOException e) {
            Map<String,String> ret = new HashMap<>();
            ret.put("code","fail");
            ret.put("msg","上传文件发生异常，请重试，多次失败请联系管理员!");
            return JSONUtil.toJsonStr(ret);
        }
    }

    /**
     * 等比压缩图片宽度
     * @param originalImage
     * @param targetWidth
     * @return
     * @throws IOException
     */
    public byte[] compressImage(MultipartFile originalImage, int targetWidth) throws IOException {
        BufferedImage bimg = ImageIO.read(originalImage.getInputStream());
        // 计算等比高度
        int srcWidth = bimg.getWidth();
        int srcHeight = bimg.getHeight();
        int newHeight = (int) ((double) srcHeight / srcWidth * targetWidth);
        BufferedImage resizedImg = new BufferedImage(targetWidth, newHeight, BufferedImage.TYPE_INT_RGB);
        resizedImg.getGraphics().drawImage(bimg, 0, 0, targetWidth, newHeight, null);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(resizedImg, "jpg", baos);
        return baos.toByteArray();
    }

    /**
     * 获取文件扩展名
     * @param fileName 文件名
     * @return 文件扩展名（不含点号）
     */
    public String getFileExtension(String fileName) {
        if (fileName == null || fileName.lastIndexOf(".") == -1) {
            return "";
        }
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    public String getBase64Image(byte[] imageBytes) {
        return Base64.getEncoder().encodeToString(imageBytes);
    }
}
